package cuiyt.juc.unsafe.collection;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cyt
 * @create 2020-09-01 8:54
 */
public class Test2 {
    static Lock lock = new ReentrantLock();

    static Integer value = 0;

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                add4();
            }, "" + i).start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(Test2.value);
    }

    public static void add() {
        for (int i = 0; i < 10000; i++) {
            Test2.value++;
        }
    }

    public synchronized static void add2() {
        for (int i = 0; i < 10000; i++) {
            Test2.value++;
        }
    }

    public static void add3() {
        for (int i = 0; i < 10000; i++) {
            synchronized (Test2.value) {
                Test2.value++;
            }
        }
    }

    public static void add4() {
        for (int i = 0; i < 10000; i++) {
            lock.lock();
            try {
                Test2.value++;
            } catch (Exception e) {
            } finally {
                lock.unlock();
            }
        }
    }

}
